#include "Heap.h"

void HeapInit(HP* php)
{
	assert(php);
	php->a = (HPdata*)malloc(sizeof(HPdata) * 4);
	if (php->a == NULL)
	{
		perror("malloc fail");
		return;
	}

	php->capacity = 4;
	php->size = 0;

}

void Swap(HPdata* p1, HPdata* p2)
{
	HPdata tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void AdjustUp(HPdata* a,int child)
{
	int parent = (child - 1) / 2;

	while (child>0)
	{
		if (a[parent] < a[child])
		{
			Swap(&a[child], &a[parent]);

			child = parent;
			parent = (child - 1) / 2;
		}
		else
			break;
	}
}

void HeapPush(HP* php, HPdata x)
{
	assert(php);

	if (php->size == php->capacity)
	{
		HPdata* tmp = (HPdata*)realloc(php->a,sizeof(HPdata) * (php->capacity)*2);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}

		php->a = tmp;
		php->capacity *= 2;

	}
	php->a[php->size] = x;
	php->size++;

	AdjustUp(php->a,php->size-1);
}

void HeapPop(HP* php)
{
	assert(php);

	Swap(&php->a[0], &php->a[php->size-1]);

	php->size--;

	Adjustdown(php->a,php->size,0);
}

void Adjustdown(HPdata* a,int n,int parent)
{
	int child = parent * 2 + 1;

	while (child<n)
	{
		//
		if (child<n && a[child+1] > a[child])
		{
			child++;
		}
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
			break;
	}

}

void Heapsort(int* a, int n)
{

	
	for (int i = 1; i < n; i++)
	{
		AdjustUp(a, i);
	}

	
	int end = n - 1;


	while (end>0)
	{
		if(a[end]<a[0])
			Swap(&a[end], &a[0]);
		end--;

		Adjustdown(a, end , 0);

	}

}